<script setup>
  import { ref, onMounted, useTemplateRef } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import HTTPserver from '@/js/HTTPserver';
  import TextEditor from '@/components/TextEditor.vue';
  import utilTool from '@/js/utilTool';

  let recoIdea = ref({
    sort: -1,
    author: '',
    title: '',
    textMini: '',
    text: '',
    date: '',
    isdel: '',
  });

  let newRecoIdea = ref({
    sort: -1,
    author: '',
    title: '',
    textMini: '',
    text: '',
    date: '',
    isdel: '',
  });
  newRecoIdea.value.date = utilTool.getDate();

  const isEdit = ref(false);
  const texteditorTitle = useTemplateRef('texteditorTitle');
  const texteditorDescription = useTemplateRef('texteditorDescription');

  onMounted(() => {
    let sort = useRoute().params.param.slice(6, -4);
    if (sort == '') {
      isEdit.value = true;
    } else {
      HTTPserver.getRecoIdeaBySort(recoIdea, sort);
    }
  });

  function saveRecoIdea() {
    newRecoIdea.value.title = texteditorTitle.value.getText();
    newRecoIdea.value.text = texteditorDescription.value.getHtml();
    newRecoIdea.value.textMini = (texteditorDescription.value.getText() + '').substring(0, 31);
    if (utilTool.isEmpty(newRecoIdea.value.title)) {
      alert('标题为空哦');
      return;
    }
    if (utilTool.isEmpty(newRecoIdea.value.text)) {
      alert('内容为空哦');
      return;
    }
    HTTPserver.addRecoIdea(newRecoIdea);
  }
  const router = useRouter();
  function back() {
    router.back();
  }
</script>

<template>
  <div style="width: 100%; min-height: 100vh; padding-left: 10rem; padding-right: 10rem">
    <div v-if="isEdit" class="color_white panel_N1">
      <TextEditor
        ref="texteditorTitle"
        class="text_H3"
        placeholder="标题"
        height="10%"
        textAlign="center"
        :scroll="false"
        :read-only="false"
        :maxLength="16"
      ></TextEditor>
      <TextEditor
        ref="texteditorDescription"
        class="text_H5"
        placeholder="正文"
        height="10rem"
        :scroll="true"
        :read-only="false"
        toolbarType="1"
      ></TextEditor>
      <button class="text_H6 button_N6_2" v-on:click="back">返回</button>
      <button class="text_H6 button_N6" v-on:click="saveRecoIdea">提交</button>
    </div>
    <div v-if="!isEdit" class="color_white panel_N1">
      <div class="text_H3 title" v-html="recoIdea.title"></div>
      <div class="text_H5 text" v-html="recoIdea.text"></div>
      <div v-if="recoIdea.author || recoIdea.date" class="text_H4 position_N1">
        {{ recoIdea.author }} 创建于 {{ recoIdea.date }}
      </div>
    </div>
  </div>
</template>
<style scoped>
  .title {
    width: 100%;
    margin-top: 4rem;
    text-align: center;
  }
  .text {
    width: 100%;
    padding: 2rem;
  }
</style>
